const ChatService = require('../services/chatService')
const logger = require('../utils/logger')
const { HTTP_STATUS } = require('../utils/constants')
const { asyncHandler } = require('../middleware/errorHandler')

class ChatController {
  /**
   * 创建新的聊天会话
   */
  static createSession = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const sessionData = req.body
    
    const session = await ChatService.createSession(userId, sessionData)
    
    res.status(HTTP_STATUS.CREATED).json({
      success: true,
      message: '聊天会话创建成功',
      data: {
        session
      }
    })
  })
  
  /**
   * 获取用户的聊天会话列表
   */
  static getUserSessions = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const {
      page = 1,
      limit = 20,
      search,
      tags,
      isPinned,
      isActive = 'true',
      sortBy = 'updatedAt',
      sortOrder = 'desc'
    } = req.query
    
    const options = {
      page: parseInt(page),
      limit: parseInt(limit),
      search,
      tags: tags ? tags.split(',') : undefined,
      isPinned: isPinned !== undefined ? isPinned === 'true' : undefined,
      isActive: isActive === 'true',
      sortBy,
      sortOrder
    }
    
    const sessions = await ChatService.getUserSessions(userId, options)
    
    res.json({
      success: true,
      data: sessions
    })
  })
  
  /**
   * 获取聊天会话详情
   */
  static getSession = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    
    const session = await ChatService.getSession(userId, sessionId)
    
    res.json({
      success: true,
      data: {
        session
      }
    })
  })
  
  /**
   * 更新聊天会话
   */
  static updateSession = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    const updateData = req.body
    
    const session = await ChatService.updateSession(userId, sessionId, updateData)
    
    res.json({
      success: true,
      message: '会话更新成功',
      data: {
        session
      }
    })
  })
  
  /**
   * 删除聊天会话
   */
  static deleteSession = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    const { permanent = 'false' } = req.query
    
    await ChatService.deleteSession(userId, sessionId, permanent === 'true')
    
    res.json({
      success: true,
      message: permanent === 'true' ? '会话已永久删除' : '会话已删除'
    })
  })
  
  /**
   * 恢复已删除的会话
   */
  static restoreSession = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    
    const session = await ChatService.restoreSession(userId, sessionId)
    
    res.json({
      success: true,
      message: '会话恢复成功',
      data: {
        session
      }
    })
  })
  
  /**
   * 发送消息
   */
  static sendMessage = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    const messageData = req.body
    
    const result = await ChatService.sendMessage(userId, sessionId, messageData)
    
    res.status(HTTP_STATUS.CREATED).json({
      success: true,
      message: '消息发送成功',
      data: result
    })
  })
  
  /**
   * 获取会话消息列表
   */
  static getSessionMessages = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    const {
      page = 1,
      limit = 50,
      role,
      search,
      sortBy = 'createdAt',
      sortOrder = 'asc'
    } = req.query
    
    const options = {
      page: parseInt(page),
      limit: parseInt(limit),
      role,
      search,
      sortBy,
      sortOrder
    }
    
    const messages = await ChatService.getSessionMessages(userId, sessionId, options)
    
    res.json({
      success: true,
      data: messages
    })
  })
  
  /**
   * 编辑消息
   */
  static editMessage = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId, messageId } = req.params
    const { content } = req.body
    
    const message = await ChatService.editMessage(userId, sessionId, messageId, content)
    
    res.json({
      success: true,
      message: '消息编辑成功',
      data: {
        message
      }
    })
  })
  
  /**
   * 删除消息
   */
  static deleteMessage = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId, messageId } = req.params
    const { permanent = 'false' } = req.query
    
    await ChatService.deleteMessage(userId, sessionId, messageId, permanent === 'true')
    
    res.json({
      success: true,
      message: permanent === 'true' ? '消息已永久删除' : '消息已删除'
    })
  })
  
  /**
   * 添加消息反应
   */
  static addMessageReaction = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId, messageId } = req.params
    const { reaction } = req.body
    
    const message = await ChatService.addMessageReaction(userId, sessionId, messageId, reaction)
    
    res.json({
      success: true,
      message: '反应添加成功',
      data: {
        message
      }
    })
  })
  
  /**
   * 移除消息反应
   */
  static removeMessageReaction = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId, messageId } = req.params
    const { reaction } = req.body
    
    const message = await ChatService.removeMessageReaction(userId, sessionId, messageId, reaction)
    
    res.json({
      success: true,
      message: '反应移除成功',
      data: {
        message
      }
    })
  })
  
  /**
   * 搜索消息
   */
  static searchMessages = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const {
      q: query,
      sessionId,
      page = 1,
      limit = 20,
      role,
      dateFrom,
      dateTo
    } = req.query
    
    if (!query) {
      return res.status(HTTP_STATUS.BAD_REQUEST).json({
        success: false,
        message: '搜索关键词不能为空'
      })
    }
    
    const options = {
      sessionId,
      page: parseInt(page),
      limit: parseInt(limit),
      role,
      dateFrom,
      dateTo
    }
    
    const results = await ChatService.searchMessages(userId, query, options)
    
    res.json({
      success: true,
      data: results
    })
  })
  
  /**
   * 导出会话
   */
  static exportSession = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    const { format = 'json' } = req.query
    
    const exportData = await ChatService.exportSession(userId, sessionId, format)
    
    if (format === 'text') {
      res.setHeader('Content-Type', 'text/plain; charset=utf-8')
      res.setHeader('Content-Disposition', `attachment; filename="chat-${sessionId}.txt"`)
      res.send(exportData)
    } else {
      res.setHeader('Content-Type', 'application/json; charset=utf-8')
      res.setHeader('Content-Disposition', `attachment; filename="chat-${sessionId}.json"`)
      res.json(exportData)
    }
  })
  
  /**
   * 批量操作会话
   */
  static batchUpdateSessions = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionIds, action, data } = req.body
    
    if (!sessionIds || !Array.isArray(sessionIds) || sessionIds.length === 0) {
      return res.status(HTTP_STATUS.BAD_REQUEST).json({
        success: false,
        message: '会话ID列表不能为空'
      })
    }
    
    const results = []
    const errors = []
    
    for (const sessionId of sessionIds) {
      try {
        let result
        switch (action) {
          case 'delete':
            result = await ChatService.deleteSession(userId, sessionId, data?.permanent || false)
            break
          case 'restore':
            result = await ChatService.restoreSession(userId, sessionId)
            break
          case 'update':
            result = await ChatService.updateSession(userId, sessionId, data)
            break
          default:
            throw new Error(`不支持的操作: ${action}`)
        }
        results.push({ sessionId, success: true, result })
      } catch (error) {
        errors.push({ sessionId, success: false, error: error.message })
      }
    }
    
    res.json({
      success: errors.length === 0,
      message: `批量操作完成，成功: ${results.length}，失败: ${errors.length}`,
      data: {
        results,
        errors
      }
    })
  })
  
  /**
   * 获取会话统计信息
   */
  static getSessionStats = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    
    const session = await ChatService.getSession(userId, sessionId)
    
    // 这里可以添加更详细的统计信息
    const stats = {
      messageCount: session.messageCount,
      totalTokens: session.metadata?.totalTokens || 0,
      totalCost: session.metadata?.totalCost || 0,
      createdAt: session.createdAt,
      lastMessageAt: session.lastMessageAt,
      tags: session.tags,
      isPinned: session.isPinned
    }
    
    res.json({
      success: true,
      data: {
        stats
      }
    })
  })
  
  /**
   * 添加会话标签
   */
  static addSessionTag = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    const { tag } = req.body
    
    const session = await ChatService.getSession(userId, sessionId)
    
    if (!session.tags.includes(tag)) {
      const updatedSession = await ChatService.updateSession(userId, sessionId, {
        tags: [...session.tags, tag]
      })
      
      res.json({
        success: true,
        message: '标签添加成功',
        data: {
          session: updatedSession
        }
      })
    } else {
      res.json({
        success: true,
        message: '标签已存在',
        data: {
          session
        }
      })
    }
  })
  
  /**
   * 移除会话标签
   */
  static removeSessionTag = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    const { tag } = req.body
    
    const session = await ChatService.getSession(userId, sessionId)
    
    const updatedTags = session.tags.filter(t => t !== tag)
    const updatedSession = await ChatService.updateSession(userId, sessionId, {
      tags: updatedTags
    })
    
    res.json({
      success: true,
      message: '标签移除成功',
      data: {
        session: updatedSession
      }
    })
  })
  
  /**
   * 切换会话置顶状态
   */
  static toggleSessionPin = asyncHandler(async (req, res) => {
    const userId = req.user.id
    const { sessionId } = req.params
    
    const session = await ChatService.getSession(userId, sessionId)
    
    const updatedSession = await ChatService.updateSession(userId, sessionId, {
      isPinned: !session.isPinned
    })
    
    res.json({
      success: true,
      message: `会话已${updatedSession.isPinned ? '置顶' : '取消置顶'}`,
      data: {
        session: updatedSession
      }
    })
  })
}

module.exports = ChatController